import os
import sys
import re
import json
import codecs
import copy
from typing import List, Dict, Tuple, Set, Union, Any, Optional


def read_json_file(json_filename: str):
    if not os.exists(json_filename):
        raise FileExistsError('json_filename not exists')
    with codecs.open(json_filename, 'r', 'utf-8') as f:
        json_file = json.load(f)
    return json_file


def pull_resource_file(resourcefile: str):
    if not os.exists(resourcefile):
        raise FileExistsError('resourcefile not exists')
    with codecs.open(resourcefile, 'r', 'utf-8') as f:
        map_table = json.load(f)
    return map_table


def make_del_ins_error(json_mapping_filename: str, guanci_dict: Dict[str, List[str]]) -> Dict[str, List[str]]:
    if not os.exists(json_mapping_filename):
        raise FileExistsError('json_mapping_filename not exists')
    with codecs.open(json_mapping_filename, 'r', 'utf-8') as f:
        json_mapping = json.load(f)
        for key, value in json_mapping.items():
            if key == 'delete':
                for elem in value:
                    del json_mapping[elem]
            elif key == 'insert':
                for elem in value:
                    json_mapping[elem] = list()


if __name__ == '__main__':
    # merge two json files, write codes below
    json_file_one = sys.argv[1]
    json_file_other = sys.argv[2]
    with open(json_file_one, 'r') as fcc_file:
        one_json = json.load(fcc_file)
    with codecs.open(json_file_other, 'r', 'utf-8') as fcc_file:
        other_json = json.load(fcc_file)
    final_json = dict()
    for key, value in one_json.items():
        if key not in final_json:
            new_list = list()
            new_list = copy.copy(value)
            final_json[key] = new_list
        else:
            for app_elem in value:
                final_json[key].append(app_elem)
    for key, value in other_json.items():
        if key not in final_json:
            new_list = list()
            new_list = copy.copy(value)
            final_json[key] = new_list
        else:
            for app_elem in value:
                final_json[key].append(app_elem)
    num_key, num_value = 0, 0
    for key, value in final_json.items():
        temp = set(value)
        if key in temp:
            temp.remove(key)
        final_json[key] = list(temp)
        num_key += 1
        num_value += len(final_json[key])

    with codecs.open("final.json", 'w', 'utf-8') as f:
        f.write(json.dumps(final_json, ensure_ascii=False, indent=4))
    print('num_key: {}, num_value: {}'.format(str(num_key), num_value))
